<template>
  <div class="my-comment-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>
            <i class="icon-comment">💬</i>
            我评论的攻略
          </h2>
          <div class="header-subtitle">记录您的精彩评论与互动</div>
        </div>
        <div class="total-count">
          <span class="count-number">{{ totalComments }}</span>
          <span class="count-text">条评论</span>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载精彩内容中...</span>
    </div>

    <!-- 空状态 -->
    <div v-else-if="comments.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="icon-empty">💭</i>
      </div>
      <h3 class="empty-title">还没有评论的攻略</h3>
      <p class="empty-description">快去发现那些精彩的旅行攻略并留下您的见解吧！</p>
      <router-link to="/strategy" class="explore-btn">
        <i class="icon-explore">🔍</i>
        探索攻略
      </router-link>
    </div>

    <!-- 评论列表 -->
    <div v-else class="comment-list">
      <div v-for="comment in comments" :key="comment.strategyCommentId" class="comment-card">
        <!-- 用户信息区 -->
        <div class="comment-user">
          <router-link :to="`/user/profile/${comment.userId}`" class="user-link">
            <img :src="comment.authorAvatar || defaultAvatar" class="user-avatar" alt="用户头像" />
            <div class="user-info">
              <h3 class="user-name">{{ comment.userName || "匿名用户" }}</h3>
              <div class="comment-time">{{ formatDate(comment.commentTime) }}</div>
            </div>
          </router-link>
        </div>
        
        <!-- 评论内容 -->
        <div class="comment-content">
          <div class="content-text">
            <p>{{ comment.commentContent }}</p>
          </div>
          
          <!-- 关联攻略 -->
          <div v-if="comment.strategyName" class="related-strategy">
            <i class="strategy-icon">📝</i>
            <router-link :to="`/homepage/strategy/detail/${comment.strategyId}`" class="strategy-link">
              {{ comment.strategyName }}
            </router-link>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="comment-actions">
          <button class="delete-btn" @click.stop="handleDeleteComment(comment)">
            <i class="delete-icon">🗑️</i>
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div v-if="showPagination && comments.length > 0" class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalComments"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MyComments',
  data() {
    return {
      comments: [],
      loading: true,
      totalComments: 0,
      currentPage: 1,
      pageSize: 10,
      showPagination: true,
      defaultAvatar: '',
      baseAvatarUrl: 'http://localhost:8080/uploads/avatar/'
    };
  },
  created() {
    window.addEventListener('storage', this.handleStorageChange);
    this.fetchMyComments();
  },
  beforeDestroy() {
    window.removeEventListener('storage', this.handleStorageChange);
  },
  watch: {
    '$route'() {
      this.fetchMyComments();
    }
  },
  methods: {
    formatDate(time) {
      if (!time) return '';
      return new Date(time).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    async fetchMyComments() {
      try {
        this.loading = true;
        const loginId = localStorage.getItem('loginId');
        const token = localStorage.getItem('token');

        if (!loginId) {
          this.resetState();
          return;
        }

        const userRes = await fetch(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`);
        const userData = await userRes.json();
        const userId = userData.userId;

        if (!userId) {
          this.resetState();
          return;
        }

        const commentRes = await fetch(
          `http://localhost:8080/sct/myCommentsByUserId?userId=${userId}&pageNum=${this.currentPage}&pageSize=${this.pageSize}`,
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Cache-Control': 'no-cache'
            }
          }
        );
        
        const pageResult = await commentRes.json();
        this.comments = (pageResult.list || []).map(comment => {
          console.log('DEBUG: Original comment userAvatar from backend:', comment.userAvatar, 'for user:', comment.userName);
          return {
            ...comment,
            authorAvatar: comment.userAvatar ? 
              (comment.userAvatar.startsWith('http') ? 
                comment.userAvatar : 
                this.baseAvatarUrl + comment.userAvatar) : 
              this.defaultAvatar
          };
        });
        this.totalComments = pageResult.total || 0;
        this.showPagination = this.totalComments > this.pageSize;

      } catch (error) {
        console.error('获取评论失败:', error);
        this.$message.error('获取评论失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    async handleDeleteComment(comment) {
      try {
        const confirm = await this.$confirm('确定要删除这条评论吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        if (!confirm) return;

        const response = await fetch(
          `http://localhost:8080/sct/delete?id=${comment.strategyCommentId}`,
          {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
          }
        );

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || '删除失败');
        }

        this.$message.success('评论删除成功');
        await this.fetchMyComments();
      } catch (error) {
        console.error('删除评论失败:', error);
        if (error !== 'cancel') {
          this.$message.error(error.message || '删除评论失败，请稍后重试');
        }
      }
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchMyComments();
    },
    handleStorageChange() {
      this.fetchMyComments();
    },
    resetState() {
      this.comments = [];
      this.totalComments = 0;
      this.showPagination = false;
    }
  }
};
</script>

<style scoped>
.my-comment-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 32px;
}

.header-content {
  background: white;
  padding: 24px 32px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-comment {
  font-size: 24px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.header-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.total-count {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(135deg, #a6a6e4 0%, #c3aadd 100%);
  color: white;
  padding: 16px 20px;
  border-radius: 12px;
  min-width: 80px;
}

.count-number {
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.count-text {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 4px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #6b7280;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

.explore-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.explore-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

/* 评论列表 */
.comment-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.comment-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  padding: 24px;
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 20px;
  align-items: flex-start;
}

.comment-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.comment-user {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 120px;
}

.user-link {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-decoration: none;
  color: inherit;
}

.user-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #e2e8f0;
  transition: all 0.3s ease;
  margin-bottom: 12px;
}

.user-link:hover .user-avatar {
  border-color: #667eea;
  transform: scale(1.05);
}

.user-info {
  text-align: center;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.comment-time {
  font-size: 12px;
  color: #9ca3af;
}

.comment-content {
  flex: 1;
  padding: 0 16px;
}

.content-text {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #e2e8f0;
}

.content-text p {
  margin: 0 0 8px 0;
  line-height: 1.6;
  color: #4b5563;
}

.content-text p:last-child {
  margin-bottom: 0;
}

.related-strategy {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #6b7280;
}

.strategy-icon {
  font-size: 16px;
}

.strategy-link {
  color: #667eea;
  text-decoration: none;
  transition: all 0.2s ease;
}

.strategy-link:hover {
  color: #764ba2;
  text-decoration: underline;
}

.comment-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.delete-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(238, 90, 36, 0.3);
}

.delete-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(238, 90, 36, 0.5);
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

.delete-icon {
  font-size: 14px;
}

/* 分页器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-comment-container {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .comment-card {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 20px;
  }
  
  .comment-user {
    flex-direction: row;
    align-items: center;
    gap: 16px;
  }
  
  .user-link {
    flex-direction: row;
    text-align: left;
  }
  
  .user-avatar {
    margin-bottom: 0;
    width: 48px;
    height: 48px;
  }
  
  .user-info {
    text-align: left;
  }
  
  .comment-actions {
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: 20px;
  }
  
  .header-left h2 {
    font-size: 24px;
  }
  
  .comment-content {
    padding: 0;
  }
}
</style>